#include "nr_device_item_server.h"

nr_device_item_server::nr_device_item_server()
{
}

nr_device_item_server::nr_device_item_server(nr_device_item_server &item_server)
{
    // Copy it 
    copy_item_server(item_server);
}

nr_device_item_server::~nr_device_item_server()
{
}

nr_device_item_server& nr_device_item_server::operator = (nr_device_item_server &item_server)
{
    // Copy it 
    copy_item_server(item_server);
    
    return *this;
}

void nr_device_item_server::copy_item_server(nr_device_item_server& item_server)
{
    // Copy sub-groups
    for(nr_device_groups::iterator it = item_server.groups().begin();
        it != item_server.groups().end(); ++it)
    {
        nr_device_group *new_group = new nr_device_group(*it.value());
        this->groups().insert(it.key(), new_group);
    }
    
    // Copy the base item data
    copy_data(item_server);
}

nr_device_item* nr_device_item_server::find_device_item_by_id(
    const nr_device_id_t &device_id)
{
    // Find in each group
    foreach(nr_device_group* group, this->groups())
    {
        nr_device_item* item = group->find_device_item_by_id(device_id);
        if (item != NULL)
            return item;
    }
    
    // Find in the sub-item list
    return nr_device_item::find_device_item_by_id(device_id);
}

void nr_device_item_server::serialize(QDataStream& data_stream)
{
    // Save the groups
    data_stream << this->groups().count();
    for(nr_device_groups::iterator it = this->groups().begin();
        it != this->groups().end(); ++it)
    {
        data_stream << it.key();
        nr_device_group* child_group = it.value();
        child_group->serialize(data_stream);
    }

    nr_device_item::serialize(data_stream);
}

void nr_device_item_server::deserialize(QDataStream& data_stream)
{
    // Get the groups
    int count = 0;
    data_stream >> count;
    
    for(int i = 0; i < count; ++i)
    {
        nr_device_id_t id;
        nr_device_group* group = new nr_device_group;

        data_stream >> id;
        group->deserialize(data_stream);
        this->groups().insert(id, group);
    }
    
    // Get the sub-items
    nr_device_item::deserialize(data_stream);
}
